package com.example.AsynTask;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;

import com.examplee.username.httpfrist_01.R;

public class ProgressBarTestActivity extends AppCompatActivity {
ProgressBar mprogressBar;
    MyAsyncTask myAsyncTask;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress_bar_test);
        mprogressBar= (ProgressBar) findViewById(R.id.pg);
        myAsyncTask= new MyAsyncTask();
        myAsyncTask.execute();//启动异步任务
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (myAsyncTask!=null && myAsyncTask.getStatus()==AsyncTask.Status.RUNNING){
//      cancel只是将对应的 AsyncTask   标记为cancel状态，并不是真正的取消
            myAsyncTask.cancel(true);

        }
    }

    class MyAsyncTask extends AsyncTask<Void,Integer,Void>{

//运行在 其他线程中，而AsyncTask的其他方法在主线程中进行
        @Override
        protected Void doInBackground(Void... params) {
            for (int i=0;i<100;i++){
                if (isCancelled()){
                   break;
                }
                publishProgress(i);
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            if (isCancelled()){
                return;
            }
            //获取进度更新值
            mprogressBar.setProgress(values[0]);
        }
    }
}
